import  os

def rename_files(dirname):
   
    a=1
    
    print os.getcwd()

    if not os.getcwd() == dirname:
        os.chdir(dirname)
    
    for fname in os.listdir(os.getcwd()):
        ext=os.path.splitext(fname)

        if ext[len(ext)-1]==".pgm":
            os.rename(fname,"1_test_%d%s"%(a,ext[len(ext)-1]))
            a +=1

    print "Files renamed in %s"%dirname


def remove_files(dirname):

    if not os.getcwd() == dirname:
        os.chdir(dirname)
    
    for fname in os.listdir(os.getcwd()):
        
        ext=os.path.splitext(fname)
        
        if ext[len(ext)-1]==".pgm":
            os.remove(fname)
   
def run_test(from_where_to_test,match,id=None):

    #test directory
    dirname = "/home/makkalot/dontmove/dontmove/dontmove/playground/denis/eigen/unin"
    copy_files_to_test(from_where_to_test,dirname)
    #first_rename them 
    rename_files(dirname)

    #then run the test
    os.chdir("..") # go one up
    f = open("yeni","a")
    
    if match:
        f.write("match_%d\n"%id)
    else:
        f.write("dismatch_%s\n"%(from_where_to_test))

    #run the c code here
    result=os.popen3("./eigenqmake tester")
    f.write(result[1].read())

 
    if match:
        f.write("endmatch\n")
    else:
        f.write("enddismatch\n")

    print "Results from test are in the file check them"
    f.close()

    remove_files(dirname)

def copy_files_to_test(src,dst):

    import shutil
    
    #remove files if there are more there
    remove_files(dst)

    if not os.getcwd() == src:
        os.chdir(src)
    

    for fname in os.listdir(src):
        ext=os.path.splitext(fname)
        
        if ext[len(ext)-1]==".pgm":
            #copy to testing directory
            shutil.copy(fname,dst)
            
    print "Copying succesfull check the destination ..."



if __name__=="__main__":
    f = open("yeni","w")
    f.close()
    #:)
    run_test("/home/makkalot/Desktop/test-resimleri/s8",False)
    run_test("/home/makkalot/Desktop/test-resimleri/s12",False)
    run_test("/home/makkalot/Desktop/test-resimleri/s23",False)
    run_test("/home/makkalot/Desktop/test-resimleri/s27",False)
    run_test("/home/makkalot/Desktop/test-resimleri/s36",False)
    run_test("/home/makkalot/Desktop/test-resimleri/s38",False)
    run_test("/home/makkalot/Desktop/test-resimleri/teyze",False)
    run_test("/home/makkalot/Desktop/test-resimleri/annem",False)
    run_test("/home/makkalot/Desktop/test-resimleri/melek",False)
    print "All tests run succesfully lucky you !"
    #copy_files_to_test("/home/makkalot/Desktop/test-resimleri/denis_test","/home/makkalot/dontmove/dontmove/dontmove/playground/denis/eigen/unin")

    #run_that_test("src","name_of_the_test","match","match_with_whom")
